//! @Author: DengLibin 
//! @Date:  2022-04-20 18:09:13
//! @Description:

use actix_web::{
    get,
    http::{header::ContentType, Method, StatusCode},
    web, Either, HttpRequest, HttpResponse, Responder, Result,
};

use actix_files::NamedFile;
use actix_session::Session;
use async_stream::stream;
use std::convert::Infallible;
use common::date;
/// @Author: DengLibin 
/// @Date:  2022-04-20 18:37:55
/// @Description: 访问文件
#[get("/favicon")]
pub async fn favicon() -> Result<impl Responder> {
    Ok(NamedFile::open("static/favicon.ico")?)
}

/// @Author: DengLibin 
/// @Date:  2022-04-20 18:38:12
/// @Description: session 访问计数
#[get("/welcome")]
pub async fn welcome(_: HttpRequest, session: Session) -> Result<HttpResponse> {
    //println!("{:?}", req);
    // session
    let mut counter = 1;
    if let Some(count) = session.get::<i32>("counter")? {
        info!("count:{}", count);
        counter = count + 1;
    }

    // set counter to session
    session.insert("counter", counter)?;
    let body = format!("<h1>Welcome</h1> {}", counter);
    // response
    Ok(HttpResponse::build(StatusCode::OK)
        .content_type(ContentType::html())
        .body(body))
}
/// @Author: DengLibin 
/// @Date:  2022-04-20 21:03:39
/// @Description: 获取系统时间
#[get("/time")]
pub async fn time() -> Result<HttpResponse> {

    let body = date::get_chrono_local_now_time_str();
    // response
    Ok(HttpResponse::build(StatusCode::OK)
        .content_type(ContentType::plaintext())
        .body(body))
}

/// 404
pub async fn default_handler(req_method: Method) -> Result<impl Responder> {
    match req_method {
        Method::GET => {
            let file = NamedFile::open("static/404.html")?.set_status_code(StatusCode::NOT_FOUND);
            Ok(Either::Left(file))
        }
        _ => Ok(Either::Right(HttpResponse::MethodNotAllowed().finish())),
    }
}

/// response body
pub async fn response_body(path: web::Path<String>) -> HttpResponse {
    let name = path.into_inner();

    HttpResponse::Ok()
        .content_type(ContentType::html())
        .streaming(stream! {
            yield Ok::<_, Infallible>(web::Bytes::from("Hello "));
            yield Ok::<_, Infallible>(web::Bytes::from(name));
            yield Ok::<_, Infallible>(web::Bytes::from("!"));
        })
}
